package com.bwie.init;

import cn.hutool.core.bean.BeanUtil;
import com.bwie.es.ESProd;
import com.bwie.mapper.ProdMapper;
import com.bwie.pojo.Prod;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author GaoYiJie
 * @Description
 * @Create 2025/2/28 9:53
 * @Version 1.0
 */
@Component
@Slf4j
public class ProdInitES implements ApplicationRunner {


    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    ProdMapper prodMapper;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //初始化ES商品数据
        log.info("开始初始化ES...");

        //检查索引是否存在
        IndexOperations indexOps = elasticsearchRestTemplate.indexOps(ESProd.class);
        if (!indexOps.exists()){
            //创建索引
            log.info("创建索引..");

            indexOps.create();

            //创建映射
            Document mapping = indexOps.createMapping();
            indexOps.putMapping(mapping);
        }

        //获取数据
        List<Prod> prods = prodMapper.selectList(null);
        //转换为ES对象
        prods.stream().forEach(str->{
            ESProd esProd = BeanUtil.toBean(str, ESProd.class);
            elasticsearchRestTemplate.save(esProd);
        });

        log.info("ES初始化完成...");
    }
}
